/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package firezenk.logic;

import firezenk.util.Errors;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.SwingWorker;

/**
 *
 * @author firezenk
 */
public class Downloader extends SwingWorker<Void, Void> {

    private static final String FICHERO = "ftp://user:pass@la.web/httpdocs/updates.txt";
    private static final String PAQUETE = "ftp://user:pass@la.web/httpdocs/ping-pong-manager.jar";
    private long downloadSize;
    private long currentSize;
    private String log;
    private URLConnection urlc;

    public Downloader() {}

    private void conectar(String dir) {
        try {
            URL url = new URL(dir);
            urlc = url.openConnection();
        } catch (IOException ex) {
            Errors.creaError("Error de entrada/salida", ex.getStackTrace());
        } catch (Exception ex) {
            Errors.creaError("Error de conexión", ex.getStackTrace());
        }
    }
    
    public void downloadLog() {
        StringBuilder sb = null;
        try {
            BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                urlc.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null)
                sb.append(inputLine);
            in.close();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            Errors.creaError("No ha sido posible descargar el documento de cambios " +
                    "de la versión, no obstante la actualización seguirá", ex.getStackTrace());
        }
        log=sb.toString();
    }

    private void downloadApp() {
        DataInputStream data = null;
        try {
            File file;
            FileOutputStream fos;
            byte s;

            data = new DataInputStream(urlc.getInputStream());
            file = new File(System.getProperty("user.dir"));
            downloadSize=file.length();
            fos = new FileOutputStream(file);
                do {
                    s = data.readByte();
                    currentSize=s;
                    if (s > 0) {
                        fos.write(s);
                    }
                } while (s > 0);
                fos.close();
        } catch (IOException ex) {
            Errors.creaErrorFatal("Error no se a podido descargar la actualización, " +
                    "el programa abortará la actualización.", ex.getStackTrace());
        }

    }

    @Override
    protected Void doInBackground() throws Exception {
        setProgress(0);
        conectar(FICHERO);
        setProgress(5);
        downloadLog();
        setProgress(10);
        conectar(PAQUETE);
        setProgress(15);
        downloadApp();
        int actSize;
        do{
            actSize=(int)(downloadSize/(int)(currentSize*100));
            setProgress(actSize);
            Thread.sleep(5);
        }while(currentSize!=downloadSize);
        setProgress(100);
        return null;
    }

    /**
     * @return the log
     */
    public String getLog() {
        return log;
    }

}
